<template>
    <div class="kva-container-box">
        <div class="kva-container">
            <home-page-header>
                <div class="kva-form-search">
                    <el-form :inline="true" ref="searchForm" :model="queryParams">
                        <el-form-item>
                            <el-button class="kva-button" type="primary" icon="Plus" @click="handleAdd">添加根菜单</el-button>
                        </el-form-item>
                        <el-form-item label="关键词：">
                            <el-input v-model="queryParams.keyword" placeholder="请输入菜单名称..." maxlength="10" />
                        </el-form-item>
                        <el-form-item>
                            <el-button class="kva-button" type="primary" icon="Search" @click.prevent="handleSearch">搜索</el-button>
                            <el-button class="kva-button" type="danger" icon="Refresh" @click.prevent="handleReset">重置</el-button>
                        </el-form-item>
                    </el-form>
                </div>
                <!-- default-expand-all -->
                <el-table
                    :data="tableData"
                    style="width: 100%; margin-bottom: 20px"
                    row-key="id"
                    border
                    stripe
                    :height="settings.tableHeight()"
                >
                    <el-table-column fixed prop="id" label="ID" align="center" width="80"/>
                    <el-table-column fixed prop="parentId" label="父ID" align="center" width="80"/>
                    <el-table-column prop="title" label="展示名字" align="center" width="110">
                        <template #default="{row}">
                            <el-input v-model="row.title" style="text-align:center"
                                      @change="handleChange(row,'title')"></el-input>
                        </template>
                    </el-table-column>
                    <el-table-column label="图标" align="center" width="120">
                        <template #default="{row}">
                            <el-icon>
                                <component :is="row.icon"/>
                            </el-icon>
                            {{ row.icon }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="path" label="访问路径" align="center" width="120"/>
                    <el-table-column prop="name" label="国际化名字" align="center" width="120"/>
                    <el-table-column prop="sort" label="排序" align="center" width="180">
                        <template #default="{row}">
                            <el-input-number v-model="row.sort" @change="handleChange(row,'sort')"></el-input-number>
                        </template>
                    </el-table-column>
                    <el-table-column label="隐藏状态" align="center" width="100">
                        <template #default="{row}">
                            <el-switch
                                inline-prompt
                                size="large"
                                v-model="row.hidden"
                                :active-value="1"
                                active-text="隐藏"
                                active-color="#ff0000"
                                :inactive-value="0"
                                inactive-text="正常"
                                inactive-color="#00ff00"
                                @change="handleChange(row,'hidden')"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column label="删除状态" align="center" width="100">
                        <template #default="{row}">
                            <el-switch
                                inline-prompt
                                size="large"
                                v-model="row.isDeleted"
                                @change="handleChange(row,'is_deleted')"
                                :active-value="1"
                                active-color="#ff0000"
                                active-text="已删除"
                                inactive-color="#00ff00"
                                inactive-text="未删除"
                                :inactive-value="0"
                            />
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" align="center" width="160">
                        <template #default="scope">
                            {{ formatTimeToStr(scope.row.createTime, "yyyy/MM/dd hh:mm:ss") }}
                        </template>
                    </el-table-column>
                    <el-table-column label="更新时间" align="center" width="160">
                        <template #default="scope">
                            {{ formatTimeToStr(scope.row.updateTime, "yyyy/MM/dd hh:mm:ss") }}
                        </template>
                    </el-table-column>
                    <el-table-column fixed="right" align="left" label="操作" width="350">
                        <template #default="{row,$index}">
                            <el-button text icon="edit" @click="handleAddChild(row)" v-if="row.parentId == 0"
                                       type="primary">添加子菜单
                            </el-button>
                            <el-button text icon="edit" @click="handleEdit(row)" type="primary">编辑</el-button>
                            <el-button text icon="Tickets" @click="handleCopy(row)" type="success">复制</el-button>
                            <el-button text icon="remove" @click="handleRemove(row)" type="danger">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </home-page-header>
        </div>
        <!--添加和修改菜单-->
        <add-sys-menu ref="addRef" @load="handleLoadData"></add-sys-menu>
    </div>
</template>

<script setup>
import {kvaMessage} from "@/utils/kvaMessage.js";
import settings from '@/settings';
import {useUserStore} from "@/stores/user.js";
import {formatTimeToStr} from '@/utils/date.js'
import {DeleteById, DeleteByIds, FindData, UpdateStatus,CopyData} from "@/api/sysMenu.js";
import AddSysMenu from "@/views/sys/components/AddSysMenu.vue";
// 定义用户状态管理
const userStore = useUserStore()

// 定义组件的ref属性
const addRef = ref()

// 定义参数
const queryParams = reactive({
    keyword: ""
})

// 定义表单数据
const tableData = ref([])

// 加载数据
const handleLoadData = async () => {
    // 调用查询菜单的接口
    const resp = await FindData(queryParams)
    // 赋值给表单容器
    tableData.value = resp.data
}

// 更新状态
const handleChange = async (row, field) => {
    // 解析值
    let value = row[field]
    // 获取参数
    let params = {id: row.id, field: field, value: value}
    // 特殊处理删除字段
    if (field == 'is_deleted') {
        params.value = row.isDeleted
    }
    // 调用更新的接口
    await UpdateStatus(params)
    kvaMessage.notifySuccess("更新成功！")
    // 判断排序
    if (field == "sort") {
        tableData.value.sort((a, b) => a.sort - b.sort);
    }
    // 判断是否隐藏
    if (field == "hidden" || field == "is_deleted"){
        userStore.handlePianaRole(0,"")
    }
}

// 添加跟菜单
const handleAdd = () => {
    addRef.value.handleOpen('', 'save', tableData.value?.length)
}
// 添加子菜单
const handleAddChild = (row) => {
    addRef.value.handleOpen(row, 'child', row.children?.length)
}

// 编辑
const handleEdit = async (row) => {
    addRef.value.handleOpen(row, 'edit', tableData.value?.length)
}

// 复制
const handleCopy = async (row) => {
    await CopyData(row.id)
    kvaMessage.notifySuccess("复制成功！")
    handleLoadData()
}

// 删除
const handleRemove = async (row) => {
    try {
        const result = await kvaMessage.confirm("删除菜单", "您确定要删除吗？")
        if (result === 'confirm') {
            // 判断是否有子菜单
            if (row.children != null) {
                // 遍历获取子菜单的id
                const ids = row.children.map(m=>m.id).join(",")
                // 批量删除的接口
                await DeleteByIds(ids)
            }
            // 调用删除接口
            await DeleteById(row.id)
            kvaMessage.notifySuccess("删除成功！")
            // 重新渲染数据
            handleLoadData()
        }
    } catch (e) {
        kvaMessage.notifyError("删除失败!")
    }

}

// 搜索
const handleSearch = () => {
    handleLoadData()
}

// 重置
const handleReset = () => {
    queryParams.keyword = ''
    handleLoadData()
}

// 生命周期
onMounted(() => {
    handleLoadData()
})
</script>

<style scoped lang="scss">

</style>
